import {createRouter, createWebHashHistory, type RouteRecordRaw} from "vue-router";
import { storeToRefs } from 'pinia'; // 新增导入
import Layout from '@/layout/index.vue';
import {useUserStore} from '@/store/modules/user';

// 1. 基础路由配置（所有用户可见）
const baseRoutes: RouteRecordRaw[] = [
    {
        path: '/',
        redirect: () => {
            return '/login';
        }
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/index.vue'),
        meta: {title: '系统登录', requiresAuth: false}
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/error/404.vue'),
        meta: {title: '页面不存在'}
    },
];

// 2. 角色路由配置
const roleRoutes: Record<string, RouteRecordRaw[]> = {
    student: [
        {
            path: '/student',
            component: Layout,
            redirect: '/student/dashboard',
            meta: {requiresAuth: true, role: 'student'},
            children: [
                {
                    path: 'dashboard',
                    name: 'StudentDashboard',
                    component: () => import('@/views/dashboard/index.vue'),
                    meta: {title: '学生工作台'}
                },
                {
                    path: 'courses',
                    name: 'StudentCourses',
                    component: () => import('@/views/courses/index.vue'),
                    meta: {title: '我的课表'}
                },
                {
                    path: 'resources',
                    name: 'StudentClasses',
                    component: () => import('@/views/resources/index.vue'),
                    meta: {title: '资源中心'}
                },
                {
                    path: 'activities',
                    name: 'StudentActivities',
                    component: () => import('@/views/activities/index.vue'),
                    meta: {title: '活动中心'}
                },
                {
                    path: 'profile',
                    name: 'StudentProfile',
                    component: () => import('@/views/profile/index.vue'),
                    meta: {title: '个人中心'}
                },
                {
                    path: 'fileViewerPDF',
                    name: 'FileViewerPDF',
                    component: () => import('@/components/FileViewerPDF.vue'),
                    meta: {title: '文件预览', hidden: true}
                },
                {
                    path: 'fileViewerExcel',
                    name: 'FileViewerExcel',
                    component: () => import('@/components/FileViewerExcel.vue'),
                    meta: {title: '文件预览', hidden: true}
                },
                {
                    path: 'fileViewerWord',
                    name: 'FileViewerWord',
                    component: () => import('@/components/FileViewerWord.vue'),
                    meta: {title: '文件预览', hidden: true}
                },
                {
                    path: 'fileViewerVideo',
                    name: 'FileViewerVideo',
                    component: () => import('@/components/FileViewerVideo.vue'),
                    meta: {title: '文件预览', hidden: true}
                },
            ]
        }
    ],
    teacher: [
        {
            path: '/teacher',
            component: Layout,
            redirect: '/teacher/dashboard',
            meta: {requiresAuth: true, role: 'teacher'},
            children: [
                {
                    path: 'dashboard',
                    name: 'TeacherDashboard',
                    component: () => import('@/views/teacher/dashboard/index.vue'),
                    meta: {title: '教师工作台'}
                },
                {
                    path: 'messages',
                    name: 'Messages',
                    component: () => import('@/views/teacher/messages/index.vue'),
                    meta: {
                        title: '消息管理',
                    }
                },
                {
                    path: 'courses',
                    name: 'TeacherCourses',
                    component: () => import('@/views/teacher/classes/index.vue'),
                    meta: {title: '课程中心'}
                },
                {
                    path: 'courses/theme-detail/:id',
                    name: 'ThemeDetail',
                    component: () => import('@/views/teacher/classes/pages/ThemeDetail.vue'),
                    meta: {title: '主题详情', hidden: true}
                },
                {
                    path: 'classes',
                    name: 'teacherClasses',
                    component: () => import('@/views/teacher/teacherClasses/index.vue'),
                    meta: {title: '班级中心'}
                },
                {
                    path: 'activities',
                    name: 'TeacherActivities',
                    component: () => import('@/views/teacher/activities/index.vue'),
                    meta: {title: '活动中心'}
                },
                {
                    path: 'profile',
                    name: 'TeacherProfile',
                    component: () => import('@/views/teacher/profile/index.vue'),
                    meta: {title: '个人中心'}
                },
                {
                    path: 'fileViewerPDF',
                    name: 'TeacherFileViewerPDF',
                    component: () => import('@/components/FileViewerPDF.vue'),
                    meta: {title: '文件预览', hidden: true}
                },
                {
                    path: 'fileViewerExcel',
                    name: 'TeacherFileViewerExcel',
                    component: () => import('@/components/FileViewerExcel.vue'),
                    meta: {title: '文件预览', hidden: true}
                },
                {
                    path: 'fileViewerWord',
                    name: 'TeacherFileViewerWord',
                    component: () => import('@/components/FileViewerWord.vue'),
                    meta: {title: '文件预览', hidden: true}
                },
                {
                    path: 'fileViewerVideo',
                    name: 'TeacherFileViewerVideo',
                    component: () => import('@/components/FileViewerVideo.vue'),
                    meta: {title: '文件预览', hidden: true}
                },
            ]
        }
    ],
    admin: [
        {
            path: '/admin',
            component: Layout,
            redirect: '/admin/dashboard',
            meta: {requiresAuth: true, role: 'admin'},
            children: [
                {
                    path: 'dashboard',
                    name: 'AdminDashboard',
                    component: () => import('@/views/dashboard/index.vue'),
                    meta: {title: '管理控制台'}
                },
                {
                    path: 'messages',
                    name: 'AdminMessages',
                    component: () => import('@/views/messages/index.vue'),
                    meta: {title: '我的消息'}
                },
                {
                    path: 'courses',
                    name: 'AdminCourses',
                    component: () => import('@/views/courses/index.vue'),
                    meta: {title: '课程中心'}
                },
                {
                    path: 'classes',
                    name: 'AdminClasses',
                    component: () => import('@/views/classes/index.vue'),
                    meta: {title: '班级中心'}
                },
                {
                    path: 'activities',
                    name: 'AdminActivities',
                    component: () => import('@/views/activities/index.vue'),
                    meta: {title: '活动中心'}
                },
                {
                    path: 'analytics',
                    name: 'AdminAnalytics',
                    component: () => import('@/views/analytics/index.vue'),
                    meta: {title: '数据中心'}
                },
                {
                    path: 'profile',
                    name: 'AdminProfile',
                    component: () => import('@/views/profile/index.vue'),
                    meta: {title: '个人中心'}
                },
            ]
        }
    ]
};

// 3. 创建路由器实例
const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        ...baseRoutes,
        ...roleRoutes.student,
        ...roleRoutes.teacher,
        ...roleRoutes.admin
    ]
});

// 4. 路由激活控制函数
export function resetActiveRoutes() {
    const userStore = useUserStore();
    const { isLoggedIn, userType } = storeToRefs(userStore); // 使用 storeToRefs

    // 移除所有带有meta.role的路由
    router.getRoutes().forEach(route => {
        if (route.meta?.role) {
            router.removeRoute(route.name as string);
        }
    });

    // 添加当前角色路由
    if (isLoggedIn.value && userType.value) {
        const activeRoutes = roleRoutes[userType.value] || [];
        activeRoutes.forEach(route => {
            if (!router.hasRoute(route.name as string)) {
                router.addRoute(route);
            }
        });
    }

    // 更新根路由重定向
    if (router.hasRoute('RootRedirect')) {
        router.removeRoute('RootRedirect');
    }
    router.addRoute({
        path: '/',
        name: 'RootRedirect',
        redirect: isLoggedIn.value && userType.value
            ? `/${userType.value}/dashboard`
            : '/login'
    });
}

// 5. 路由守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    const { isLoggedIn, userType, isInitialized } = storeToRefs(userStore); // 使用 storeToRefs

    // 处理登录页的重定向参数
    if (to.path === '/login' && to.query.redirect) {
        const redirectPath = String(to.query.redirect).replace(/^#/, '');
        return next({path: '/login', query: {redirect: redirectPath}});
    }

    // 初始化用户状态
    if (!isInitialized.value) {
        console.log('🔄 开始初始化用户状态...');
        try {
            await userStore.initialize();
            console.log('✅ 用户状态初始化完成:', {
                用户类型: userType.value,
                是否登录: isLoggedIn.value
            });

            resetActiveRoutes();
            console.log('✅ 路由重置完成');
        } catch (error) {
            console.error('❌ 用户状态初始化失败:', error);
            return next('/login');
        }
    }

    // 认证检查
    if (to.meta.requiresAuth) {
        console.log('🔐 进行认证检查...');
        if (!isLoggedIn.value) {
            console.log('❌ 未登录，跳转到登录页');
            return next({path: '/login', query: {redirect: to.fullPath}});
        }

        // 权限检查：管理员可以访问所有页面
        if (to.meta.role && to.meta.role !== userType.value) {
            if (userType.value === 'admin') {
                console.log('👑 管理员权限，允许访问所有页面');
                return next();
            } else {
                console.log('❌ 权限不足，跳转到404');
                return next('/404');
            }
        }
    }

    console.log('✅ 路由守卫通过，继续导航');
    next();
});

export default router;
